package com.liusy.taskengine.jobmodel;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.liusy.common.ClassHelp;
import com.liusy.taskengine.JobTask;
import com.liusy.taskengine.taskmodel.ITaskModel;


/**
 * 数据库 任务池接口（任务源） 将任务池中的任务进行分页计算 
 * 
 * @author liusy 2012-12-13
 */
public abstract class AbstractJobModel implements IJobModel{

	private static Logger log = Logger.getLogger(AbstractJobModel.class);
	
	//名字
	protected String jobModelName= "任务池........";
	
	
	//每次取多少任务
	protected int pageSize = 20000;
	
	//第几次取任务
	protected int pageIndex = 0;
	
	//任务池中的任务不足pageSize时    最后一次取任务的个数
	protected int lastTaskNum = 0;
	
	//任务处理者
	protected String sqlExecuteModelClassStr = "";
	
	private List<Object> list = null;
	
	
	//任务模型
	protected String sqlTaskModelClassStr = "";
	
	
	
	public AbstractJobModel(String jobModelName,String sqlTaskModelClassStr) {
		this.sqlTaskModelClassStr = sqlTaskModelClassStr;
		this.jobModelName  =jobModelName;
	}
	
	public AbstractJobModel(String jobModelName,int pageSize,String sqlTaskModelClassStr){
		this.jobModelName  =jobModelName;
		this.pageSize= pageSize;
		this.sqlTaskModelClassStr = sqlTaskModelClassStr;
	}
	public AbstractJobModel(String sqlTaskModelClassStr) {
		this.sqlTaskModelClassStr = sqlTaskModelClassStr;
	}
	
	public AbstractJobModel(int pageSize,String sqlTaskModelClassStr){
		this.pageSize= pageSize;
		this.sqlTaskModelClassStr = sqlTaskModelClassStr;
	}
	
	/*
	 * 从任务池中获取要发布的任务
	 * 
	 * (non-Javadoc)
	 * @see com.liusy.taskengine.IJobModel#AddReleaseTask(com.liusy.taskengine.JobTask)
	 */
	@Override
	public void AddReleaseTask(JobTask jt) {
			
			++pageIndex;
		
			list = getTaskPoolData();
			
			if(null==list||list.size()<=0)
			{
				jt.setJobTaskFinish(true);
				log.info("从["+jobModelName+"]中取出的任务数："+this.getTaskPoolCount());
				return ;
			}
			for (Object obj : list) {
				
				jt.AddReleaseTask(this.getTaskModel(obj));
			}
			
			this.lastTaskNum = list.size();
			
			if(list.size()!=pageSize)
			{
				//任务池中没有任务了。。
				jt.setJobTaskFinish(true);
				log.info("从["+jobModelName+"]中取出的任务数："+this.getTaskPoolCount());
			}
	}
	
	/**
	 * 从任务池中取任务的数量
	 * 
	 */
	public long getTaskPoolCount(){
		
		return ((pageIndex-1)*pageSize)+lastTaskNum;
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.liusy.taskengine.jobmodel.IJobModel#getTaskModel(java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	@Override
	public ITaskModel getTaskModel(Object o) {
		
		Map<String,Object> map = (Map<String, Object>) o ;
		return (ITaskModel)ClassHelp.newObjectInstance(sqlTaskModelClassStr,new Class []{Map.class}, map);
	}
	
}
